<script setup>
import { ref, computed, onMounted, onActivated, nextTick } from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import request from '@/utils/request'
// 组件导入（已注释，改为直接渲染）
// import ApplicantView from './components/ApplicantView.vue'
// import ApproverView from './components/ApproverView.vue'
// import WarehouseManagerView from './components/WarehouseManagerView.vue'

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()

// 用户角色管理 - 从用户store获取当前角色
const currentUserRole = ref(userStore.userInfo.role || 'applicant')

// 角色选项（已注释，不再需要手动切换）
// const roleOptions = [
//   { text: '申请人', value: 'applicant' },
//   { text: '审批人', value: 'approver' }, 
//   { text: '仓库管理员', value: 'warehouse_manager' }
// ]

// 角色标题映射
const roleTitleMap = {
  'applicant': '我的出库申请',
  'approver': '待审批申请',
  'warehouse_manager': '出库管理'
}

// 搜索相关
const searchValue = ref('')

// 出库状态常量
const OutboundStatus = {
  DRAFT: 'draft',           // 草稿（未提交）
  SUBMITTED: 'submitted',   // 已提交
  INVENTORY_CHECK: 'inventory_check', // 库存检查
  INVENTORY_SUFFICIENT: 'inventory_sufficient', // 库存充足
  OFFLINE_PROCESSING: 'offline_processing', // 线下办理中
  PROCEDURES_UPLOADED: 'procedures_uploaded', // 手续已上传
  COMPLETED: 'completed',   // 已完成
  REJECTED: 'rejected'      // 已驳回
}

// 数据加载状态
const loading = ref(false)
const error = ref('')

// 出库申请列表数据
const applications = ref([])

// 状态映射
const statusMap = {
  [OutboundStatus.DRAFT]: { text: '未提交', color: '#969799' },
  [OutboundStatus.SUBMITTED]: { text: '已提交', color: '#ff976a' },
  [OutboundStatus.INVENTORY_CHECK]: { text: '库存检查', color: '#1989fa' },
  [OutboundStatus.INVENTORY_SUFFICIENT]: { text: '库存充足', color: '#07c160' },
  [OutboundStatus.OFFLINE_PROCESSING]: { text: '线下办理中', color: '#feca57' },
  [OutboundStatus.PROCEDURES_UPLOADED]: { text: '手续已上传', color: '#52c41a' },
  [OutboundStatus.COMPLETED]: { text: '已完成', color: '#52c41a' },
  [OutboundStatus.REJECTED]: { text: '已驳回', color: '#ee0a24' }
}

// 过滤后的申请列表
const filteredApplications = computed(() => {
  if (!searchValue.value.trim()) {
    return applications.value
  }
  return applications.value.filter(app => 
    app.title?.toLowerCase().includes(searchValue.value.toLowerCase()) ||
    app.description?.toLowerCase().includes(searchValue.value.toLowerCase())
  )
})

// 获取出库申请列表
async function fetchOutboundList() {
  loading.value = true
  error.value = ''
  
  try {
    const response = await request.get('/api/outbound/list')
    
    if (response.code === 0 && response.applications) {
      // 根据后端返回的数据结构进行适配
      applications.value = response.applications.map(item => ({
        id: item.applicationId || item.id,
        title: item.applicationName || '未命名申请',
        status: mapStatusFromChinese(item.status),
        modifyTime: item.submitTime || item.updateTime || item.createTime || '未知时间',
        description: item.description || '无描述',
        applicant: item.applicantName || '未知申请人',
        department: item.deptName || '未知部门',
        applicationNo: item.applicationNo,
        submitTime: item.submitTime
      }))
    } else {
      // 如果后端没有返回数据，使用空数组
      applications.value = []
    }
  } catch (err) {
    console.error('获取出库申请列表失败:', err)
    error.value = '获取数据失败，请稍后重试'
    
    // 如果是网络错误或认证错误，显示相应提示
    if (err.response?.status === 401) {
      error.value = '登录已过期，请重新登录'
    } else if (err.response?.status === 403) {
      error.value = '没有权限访问此功能'
    } else if (err.code === 'NETWORK_ERROR') {
      error.value = '网络连接失败，请检查网络设置'
    }
  } finally {
    loading.value = false
  }
}

// 将中文状态映射为英文状态码
function mapStatusFromChinese(chineseStatus) {
  const statusMap = {
    '草稿': 'draft',
    '未提交': 'draft',
    '已提交': 'submitted',
    '库存检查': 'inventory_check',
    '库存充足': 'inventory_sufficient',
    '线下办理中': 'offline_processing',
    '手续已上传': 'procedures_uploaded',
    '已完成': 'completed',
    '已驳回': 'rejected'
  }
  return statusMap[chineseStatus] || 'draft'
}

// 刷新数据
async function refreshData() {
  await fetchOutboundList()
}

// 新建申请
function createNewApplication() {
  router.push('/outbound/detail?mode=create')
}

// 搜索功能
function onSearch() {
  showToast({
    message: `搜索: ${searchValue.value}`,
    duration: 1000
  })
}

// 清空搜索
function onClearSearch() {
  searchValue.value = ''
}

// 页面激活时恢复滚动位置并刷新数据
onActivated(() => {
  const savedPosition = sessionStorage.getItem('outbound_scroll_position')
  if (savedPosition) {
    // 使用 nextTick 确保 DOM 更新后再滚动
    nextTick(() => {
      window.scrollTo(0, parseInt(savedPosition))
      // 清除保存的位置
      sessionStorage.removeItem('outbound_scroll_position')
    })
  }
  
  // 刷新数据
  refreshData()
})

// 页面挂载时获取数据
onMounted(() => {
  fetchOutboundList()
})

// 角色切换（已注释，角色由登录后的用户权限决定）
// function onRoleChange(role) {
//   currentUserRole.value = role
//   showToast({
//     message: `已切换到${roleOptions.find(r => r.value === role)?.text}视角`,
//     duration: 1500
//   })
// }

// 申请人操作处理
function handleViewDetails(application) {
  // 保存当前滚动位置，返回时可以恢复
  sessionStorage.setItem('outbound_scroll_position', window.scrollY.toString())
  
  // 根据状态决定是否可以编辑
  // 只有草稿状态（未提交）可以编辑，其他状态都是只读
  const mode = application.status === OutboundStatus.DRAFT ? 'edit' : 'view'
  router.push(`/outbound/detail?id=${application.id}&mode=${mode}`)
}

function handleEditApplication(application) {
  router.push(`/outbound/detail?id=${application.id}&mode=edit`)
}

async function handleCancelApplication(application) {
  try {
    // 调用取消申请接口
    const response = await request.post(`/api/outbound/cancel/${application.id}`)
    
    if (response.code === 0) {
      showToast({
        message: `已取消申请: ${application.title}`,
        duration: 2000
      })
      // 刷新数据
      await refreshData()
    } else {
      showToast({
        message: response.msg || '取消申请失败',
        duration: 2000
      })
    }
  } catch (err) {
    console.error('取消申请失败:', err)
    showToast({
      message: '操作失败，请稍后重试',
      duration: 2000
    })
  }
}

// 审批人操作处理
async function handleApproveApplication(application) {
  try {
    // 调用审批通过接口
    const response = await request.post(`/api/outbound/approve/${application.id}`)
    
    if (response.code === 0) {
      showToast({
        message: `已审批通过: ${application.title}`,
        duration: 2000
      })
      // 刷新数据
      await refreshData()
    } else {
      showToast({
        message: response.msg || '审批失败',
        duration: 2000
      })
    }
  } catch (err) {
    console.error('审批失败:', err)
    showToast({
      message: '操作失败，请稍后重试',
      duration: 2000
    })
  }
}

async function handleRejectApplication(application) {
  try {
    // 调用拒绝申请接口
    const response = await request.post(`/api/outbound/reject/${application.id}`)
    
    if (response.code === 0) {
      showToast({
        message: `已拒绝申请: ${application.title}`,
        duration: 2000
      })
      // 刷新数据
      await refreshData()
    } else {
      showToast({
        message: response.msg || '拒绝失败',
        duration: 2000
      })
    }
  } catch (err) {
    console.error('拒绝申请失败:', err)
    showToast({
      message: '操作失败，请稍后重试',
      duration: 2000
    })
  }
}

// // 仓库管理员操作处理
// async function handleStartOfflineProcessing(application) {
//   try {
//     // 调用开始线下处理接口
//     const response = await request.post(`/outbound/start-offline-processing/${application.id}`)
    
//     if (response.code === 0) {
//       showToast({
//         message: `开始线下处理: ${application.title}`,
//         duration: 2000
//       })
//       // 刷新数据
//       await refreshData()
//     } else {
//       showToast({
//         message: response.msg || '开始线下处理失败',
//         duration: 2000
//       })
//     }
//   } catch (err) {
//     console.error('开始线下处理失败:', err)
//     showToast({
//       message: '操作失败，请稍后重试',
//       duration: 2000
//     })
//   }
// }

async function handleCompleteOutbound(application) {
  try {
    // 调用完成出库接口
    const response = await request.post(`/api/outbound/complete/${application.id}`)
    
    if (response.code === 0) {
      showToast({
        message: `出库完成: ${application.title}`,
        duration: 2000
      })
      // 刷新数据
      await refreshData()
    } else {
      showToast({
        message: response.msg || '完成出库失败',
        duration: 2000
      })
    }
  } catch (err) {
    console.error('完成出库失败:', err)
    showToast({
      message: '操作失败，请稍后重试',
      duration: 2000
    })
  }
}
</script>

<template>
  <div class="outbound-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">{{ roleTitleMap[currentUserRole] }}</h1>
      <!-- <div class="role-info"></div> -->
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <van-search
        v-model="searchValue"
        placeholder="请输入关键词"
        @search="onSearch"
        @clear="onClearSearch"
        background="#f8f9fa"
        shape="round"
      />
      
      <!-- 新建申请按钮 (仅申请人可见) -->
      <van-button
        v-if="currentUserRole === 'applicant'"
        type="primary"
        size="normal"
        round
        class="new-btn"
        @click="createNewApplication"
      >
        新建申请
      </van-button>
    </div>

    <!-- 申请列表 -->
    <div class="application-list">
      <!-- 加载状态 -->
      <van-loading v-if="loading" class="loading-container" size="24px">
        加载中...
      </van-loading>
      
      <!-- 错误状态 -->
      <van-empty 
        v-else-if="error" 
        :description="error" 
        image="error"
      >
        <van-button 
          type="primary" 
          size="small" 
          @click="refreshData"
        >
          重试
        </van-button>
      </van-empty>
      
      <!-- 空数据状态 -->
      <van-empty 
        v-else-if="filteredApplications.length === 0" 
        description="暂无出库申请记录" 
        image="search"
      />
      
      <!-- 统一的申请列表视图 -->
      <div v-else class="applications-container">
        <div 
          v-for="application in filteredApplications" 
          :key="application.id" 
          class="application-card"
        >
          <div class="card-header">
            <h3 class="application-title">{{ application.title }}</h3>
            <span 
              class="status-tag" 
              :style="{ backgroundColor: statusMap[application.status]?.color || '#969799' }"
            >
              {{ statusMap[application.status]?.text || '未知状态' }}
            </span>
          </div>
          
          <div class="card-content">
            <div v-if="application.applicationNo" class="info-row">
              <span class="label">申请编号：</span>
              <span class="time-value">{{ application.applicationNo }}</span>
            </div>
            <div class="info-row">
              <span class="label">申请时间：</span>
              <span class="time-value">{{ application.modifyTime }}</span>
            </div>
            <div class="info-row">
              <span class="label">申请内容：</span>
              <span class="desc-value">{{ application.description }}</span>
            </div>
            <div v-if="application.applicant" class="info-row">
              <span class="label">申请人：</span>
              <span class="desc-value">{{ application.applicant }}</span>
            </div>
            <!-- <div v-if="application.department" class="info-row">
              <span class="label">部门：</span>
              <span class="desc-value">{{ application.department }}</span>
            </div> -->
          </div>
          
          <div class="card-actions">
            <van-button 
              size="small" 
              class="detail-btn"
              type="primary" 
              @click="handleViewDetails(application)"
            >
              详情
            </van-button>
            
            <!-- 根据角色显示不同操作按钮 -->
            <!-- <template v-if="currentUserRole === 'applicant' && application.status === OutboundStatus.DRAFT">
              <van-button 
                size="small" 
                type="warning" 
                @click="handleEditApplication(application)"
              >
                编辑
              </van-button>
              <van-button 
                size="small" 
                type="danger" 
                @click="handleCancelApplication(application)"
              >
                取消
              </van-button>
            </template> -->
            
            <!-- <template v-if="currentUserRole === 'approver' && application.status === OutboundStatus.SUBMITTED">
              <van-button 
                size="small" 
                type="success" 
                @click="handleApproveApplication(application)"
              >
                通过
              </van-button>
              <van-button 
                size="small" 
                type="danger" 
                @click="handleRejectApplication(application)"
              >
                拒绝
              </van-button>
            </template> -->
            
            <!-- <template v-if="currentUserRole === 'warehouse_manager' && application.status === OutboundStatus.INVENTORY_SUFFICIENT">
              <van-button 
                size="small" 
                type="primary" 
                @click="handleStartOfflineProcessing(application)"
              >
                开始线下处理
              </van-button>
            </template> -->
            
            <template v-if="currentUserRole === 'warehouse_manager' && application.status === OutboundStatus.OFFLINE_PROCESSING">
              <van-button 
                size="small" 
                type="success" 
                @click="handleCompleteOutbound(application)"
              >
                完成出库
              </van-button>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 下拉刷新提示 -->
    <van-pull-refresh 
      v-model="loading" 
      @refresh="refreshData"
      :disabled="loading"
    >
      <div class="pull-refresh-content">
        <!-- 内容已在上方显示 -->
      </div>
    </van-pull-refresh>
  </div>
</template>

<style scoped>
.outbound-page {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 60px; /* 为底部导航留出空间 */
}

.page-header {
  background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
  padding: 20px 16px;
  color: white;
  text-align: center;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  position: relative;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

/* .role-info {
  margin-top: 8px;
  font-size: 14px;
  opacity: 0.9;
  font-weight: 400;
} */

/* 角色切换样式（已注释）
.role-switch {
  position: absolute;
  top: 16px;
  right: 16px;
  min-width: 100px;
}

.role-switch :deep(.van-dropdown-menu) {
  background: transparent;
  box-shadow: none;
}

.role-switch :deep(.van-dropdown-menu__bar) {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  height: 32px;
}

.role-switch :deep(.van-dropdown-menu__bar) {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  height: 32px;
}

.role-switch :deep(.van-dropdown-item) {
  color: white;
  font-size: 14px;
  text-align: center;
}
*/

.search-section {
  padding: 16px;
  background: white;
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-bottom-left-radius: 12px;
  border-bottom-right-radius: 12px;
}

.search-section :deep(.van-search) {
  flex: 1;
  padding: 0;
}

.new-btn {
  flex-shrink: 0;
  height: 36px;
  padding: 0 20px;
  background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
  border: none;
}

.application-list {
  padding: 16px 0;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
  color: #969799;
}

.applications-container {
  padding: 16px 0;
}

.application-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.application-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.application-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.status-tag {
  color: white;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  flex-shrink: 0;
}

.card-content {
  margin-bottom: 16px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
  gap: 8px;
}

.label {
  color: #7c8db5;
  font-size: 14px;
  font-weight: 500;
  min-width: 80px;
  flex-shrink: 0;
}

.time-value,
.desc-value {
  color: #5a6c7d;
  font-size: 14px;
  flex: 1;
  line-height: 1.4;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

.detail-btn {
  background: linear-gradient(135deg, #6b9aff 0%, #2d76ff 100%);
  border: none;
  min-width: 80px;
}

.pull-refresh-content {
  min-height: 100px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .search-section {
    flex-direction: row;
    gap: 10px;
  }
  
  .new-btn {
    width: 40%;
  }
  
  .application-info {
    gap: 6px;
  }
  
  .info-row {
    /* 允许内容换行展示完整信息 */
    flex-direction: row;
    align-items: flex-start;
    gap: 6px;
    flex-wrap: wrap;
  }
  
  .label {
    min-width: 66px;
    white-space: nowrap;
  }
  
  .time-value,
  .desc-value {
    white-space: normal;
    overflow: visible;
    text-overflow: clip;
  }
}

/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
  .outbound-page {
    background-color: #1a1a1a;
  }
  
  .application-card {
    background: #2c2c2c;
    border-color: #404040;
  }
  
  .application-title {
    color: #e0e0e0;
  }
  
  .label {
    color: #a0a0a0;
  }
  
  .time-value,
  .desc-value {
    color: #c0c0c0;
  }
}
</style>

<route lang="json5">
{
  name: 'Outbound',
  meta: {
    title: '出库管理'
  }
}
</route>
